package com.supplychainapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.supplychainapi.dao.prod.TbshopMapper;
import com.supplychainapi.dao.prod.TbuserMapper;
import com.supplychainapi.domain.account.AuthEntity;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.domain.account.*;
import com.supplychainapi.model.Tbshop;
import com.supplychainapi.model.Tbuser;
import com.supplychainapi.service.TbuserService;
import com.supplychainapi.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class TbuserServiceImpl implements TbuserService {
    @Autowired
    private TbuserMapper tbuserMapper;

    @Autowired
    private TbshopMapper tbshopMapper;

    @Autowired
    private RedisServiceImpl redisService;

    @Override
    public int save(Tbuser user) {
        return tbuserMapper.insertSelective(user);
    }

    @Override
    public Tbuser findOne(Tbuser user) {
        return tbuserMapper.selectOne(user);
    }

    @Override
    public Map<String, Map<String, String>> findAllAuth() {
        List<AuthProgDtlEntity> list = tbuserMapper.findAllAuth();

        Map<String, Map<String, String>> authMap = null;

        list.forEach((AuthProgDtlEntity auth) -> {
            String progId = auth.getFsProgId();
            String progDtlId = auth.getFsProgDtlId();
            Map<String, String> map = null;
            map.put(progDtlId, progId + "_" + progDtlId);
            authMap.put(progId, map);
        });
        return authMap;
    }

    @Override
    public boolean LoginCache(String fsShopGUID, String jwtToken, Tbuser tbuser) {
        // 查询当前店铺信息
        Tbshop filter = new Tbshop();
        filter.setFsShopGUID(fsShopGUID);
        Tbshop tbshop = tbshopMapper.selectOne(filter);
        // 查询当前用户所拥有的权限
        List<AuthProgDtlEntity> userList = tbuserMapper.findUserAuth(fsShopGUID, tbuser.getFsUserId());
        HashMap<String, HashMap<String, String>> authMap = new HashMap<String, HashMap<String, String>>();

        userList.forEach((AuthProgDtlEntity auth) -> {
            String progId = auth.getFsProgId();
            String progDtlId = auth.getFsProgDtlId();
            HashMap<String, String> smap = new HashMap<String, String>();
            if (authMap.containsKey(progId)) {
                smap = authMap.get(progId);
            }
            smap.put(progDtlId, progId + "_" + progDtlId);
            authMap.put(progId, smap);
        });

        Integer fiShopKind = Integer.valueOf(tbshop.getFiShopKind());
        LoginCache loginCache = new LoginCache();
        loginCache.setFsShopGUID(fsShopGUID);
        loginCache.setFiShopKind(fiShopKind);
        loginCache.setFsShopName(tbshop.getFsShopName());
        loginCache.setFsShopType(CommonUtil.getShopType(fiShopKind));
        loginCache.setFsUserId(tbuser.getFsUserId());
        loginCache.setFsUserName(tbuser.getFsUserName());

        // 设置当前用户所有用的权限缓存
        loginCache.setAuth(authMap);

        // 获得用户登录str
        String loginCacheStr = JSONObject.toJSONString(loginCache);

        // 将当前用户session缓存到redis中, 默认永不过期
        // TODO 缓存过期时间设计
        redisService.set(jwtToken, loginCacheStr);

        return false;
    }

    @Override
    public boolean AccountInfoCache(String fsShopGUID, String jwtToken, Tbuser tbuser) {
        // 查询当前店铺信息
        Tbshop filter = new Tbshop();
        filter.setFsShopGUID(fsShopGUID);
        Tbshop tbshop = tbshopMapper.selectOne(filter);
        // 查询当前用户所拥有的权限
        List<AuthProgDtlEntity> userList = tbuserMapper.findUserAuth(fsShopGUID, tbuser.getFsUserId());
        HashMap<String, HashMap<String, String>> authMap = new HashMap<String, HashMap<String, String>>();
        userList.forEach((AuthProgDtlEntity auth) -> {
            String progId = auth.getFsProgId();
            String progDtlId = auth.getFsProgDtlId();
            HashMap<String, String> smap = new HashMap<String, String>();
            if (authMap.containsKey(progId)) {
                smap = authMap.get(progId);
            }
            smap.put(progDtlId, progId + "_" + progDtlId);
            authMap.put(progId, smap);
        });

        Integer fiShopKind = Integer.valueOf(tbshop.getFiShopKind());
        AccountInfoEntity accountInfoEntity = new AccountInfoEntity();
        accountInfoEntity.setFsShopGUID(fsShopGUID);
        accountInfoEntity.setFiShopKind(fiShopKind);
        accountInfoEntity.setFsShopName(tbshop.getFsShopName());
        accountInfoEntity.setFsShopType(CommonUtil.getShopType(fiShopKind));
        accountInfoEntity.setFsUserId(tbuser.getFsUserId());
        accountInfoEntity.setFsUserName(tbuser.getFsUserName());

        // 设置当前用户所有用的权限缓存
        accountInfoEntity.setAuth(authMap);

        // 获得用户登录str
        String accountInfoStr = JSONObject.toJSONString(accountInfoEntity);

        // 将当前用户session缓存到redis中, 默认永不过期
        // TODO 缓存过期时间设计
        redisService.set(jwtToken, accountInfoStr);

        return true;
    }

    /**
     * 查询当前总部下发用户的总部店铺id
     *
     * @param fsShopGUID
     * @param fsUserId
     * @return
     */
    @Override
    public String findUserCompanyGUID(String fsShopGUID, String fsUserId) {
        HashMap<String, String> info = tbuserMapper.findUserCompanyGUID(fsShopGUID, fsUserId);
        if (info != null) {
            return info.get("fsCompanyGUID");
        }
        return "";
    }

    /**
     * 查询当前用户管理的门店列表
     *
     * @param fsShopGUID
     * @param fsUserId
     * @return
     */
    @Override
    public List<UserShopEntity> findUserShopList(String fsShopGUID, String fsUserId) {
        return tbuserMapper.findUserShopList(fsShopGUID, fsUserId);
    }

    /**
     * 查询当前用户所拥有的权限列表
     * @param fsShopGUID
     * @param fsUserId
     * @return
     */
    @Override
    public List<AuthEntity> findUserAuthList(String fsShopGUID, String fsUserId) {

        List<UserRoleEntity> userRoleList = tbuserMapper.findUserRole(fsShopGUID, fsUserId);

        final boolean[] isAdmin = {false};
        userRoleList.forEach((UserRoleEntity userRole) -> {
            // 角色id为888 890 889的返回全部权限，因为888-系统商管理员，890-公司管理员，889-门店管理员
            if (Arrays.asList(new String[]{"888", "890", "889"}).contains(userRole.getFsRoleId())) {
                isAdmin[0] = true;
            }
        });

        List<AuthProgDtlEntity> authList;
        if (isAdmin[0]) {
            authList = tbuserMapper.findAllAuth();
        } else {
            authList = tbuserMapper.findUserAuth(fsShopGUID, fsUserId);
            HashMap<String, String> hashMap = new HashMap<String, String>();
            List<AuthProgDtlEntity> allAuthList = new ArrayList<AuthProgDtlEntity>();

            authList.forEach((AuthProgDtlEntity authEntity) -> {
                String fsProgId = authEntity.getFsProgId();
                String fsProgDtlId = authEntity.getFsProgDtlId();
                AuthProgDtlEntity auth = new AuthProgDtlEntity();
                auth.setFsProgId(fsProgId);
                auth.setFsProgDtlId(fsProgDtlId);
                if (!hashMap.containsKey(fsProgId + "_" + fsProgDtlId)) {
                    allAuthList.add(auth);
                }
                hashMap.put(fsProgId + "_" + fsProgDtlId, "1");
            });
            authList = allAuthList;
        }

        List<AuthEntity> tAuthList = new ArrayList<AuthEntity>();

        authList.forEach((AuthProgDtlEntity authEntity) -> {
            AuthEntity tAuth = new AuthEntity();
            tAuth.setFsProgId(authEntity.getFsProgId());
            tAuth.setFsProgDtlId(authEntity.getFsProgDtlId());
            tAuthList.add(tAuth);
        });

        return tAuthList;
    }

    /**
     * 获取系统商用户权限列表
     * @param fsShopGUID
     * @param fsUserId
     * @return
     */
    @Override
    public SystemAuthEntity findSysUserAuth(String fsShopGUID, String fsUserId) {
        List<UserRoleEntity> userRoleList = tbuserMapper.findUserRole(fsShopGUID, fsUserId);

        final boolean[] isAdmin = {false};
        userRoleList.forEach((UserRoleEntity userRole) -> {
            // 角色id为888 890 889的返回全部权限，因为888-系统商管理员，890-公司管理员，889-门店管理员
            if (Arrays.asList(new String[]{"888", "890", "889"}).contains(userRole.getFsRoleId())) {
                isAdmin[0] = true;
            }
        });
        SystemAuthEntity s = new SystemAuthEntity();
        // 管理员
        if (isAdmin[0]) {
            List<AuthProgDtlEntity> allAuthList = tbuserMapper.findAllAuth();
            List<AuthEntity> A = findAllAuthByShopType("A", allAuthList);
            List<AuthEntity> C = findAllAuthByShopType("C", allAuthList);
            List<AuthEntity> D = findAllAuthByShopType("D", allAuthList);

            s.setA(A);
            s.setC(C);
            s.setD(D);
            return s;
        } else {
            List<AuthProgDtlEntity> userAuthList = tbuserMapper.findUserAuth(fsShopGUID, fsUserId);

            List<AuthEntity> A = new ArrayList<AuthEntity>();
            List<AuthEntity> C = new ArrayList<AuthEntity>();
            List<AuthEntity> D = new ArrayList<AuthEntity>();

            HashMap<String, String> A_Map = new HashMap<String, String>();
            HashMap<String, String> C_Map = new HashMap<String, String>();
            HashMap<String, String> D_Map = new HashMap<String, String>();

            userAuthList.forEach((AuthProgDtlEntity authProgDtlEntity) -> {
                Integer fiShopKind = authProgDtlEntity.getFiShopKind();
                String fsProgId = authProgDtlEntity.getFsProgId();
                String fsProgDtlId = authProgDtlEntity.getFsProgDtlId();
                AuthEntity auth = new AuthEntity();
                auth.setFsProgId(fsProgId);
                auth.setFsProgDtlId(fsProgDtlId);

                if (fiShopKind == 0) {
                    if (!A_Map.containsKey("A_" + fsProgId + fsProgDtlId)) {
                        A.add(auth);
                    }
                    A_Map.put("A_" + fsProgId + fsProgDtlId, "1");
                } else if (fiShopKind == 3) {
                    if (!C_Map.containsKey("C_" + fsProgId + fsProgDtlId)) {
                        C.add(auth);
                    }
                    C_Map.put("C_" + fsProgId + fsProgDtlId, "1");
                } else if (fiShopKind == 7) {
                    if (!D_Map.containsKey("D_" + fsProgId + fsProgDtlId)) {
                        D.add(auth);
                    }
                    D_Map.put("D_" + fsProgId + fsProgDtlId, "1");
                }
                s.setA(A);
                s.setC(C);
                s.setD(D);
            });
            return s;
        }
    }

    /**
     * 根据门店类型获取所有权限列表
     * @param fsShopType A=系统商;C=公司;D=门店;
     * @return
     */
    private List<AuthEntity> findAllAuthByShopType(String fsShopType, List<AuthProgDtlEntity> allAuthList) {
        if (allAuthList == null) {
            allAuthList = tbuserMapper.findAllAuth();
        }

        List<AuthEntity> authList = new ArrayList<AuthEntity>();

        allAuthList.forEach((AuthProgDtlEntity authEntity) -> {
            String fsProgLvl = authEntity.getFsProgLvl();
            AuthEntity auth = new AuthEntity();
            if (fsProgLvl.contains(fsShopType)) {
                auth.setFsProgId(authEntity.getFsProgId());
                auth.setFsProgDtlId(authEntity.getFsProgDtlId());
                authList.add(auth);
            }
        });

        return authList;
    }
}